package com.ctshk.rpc.order.scenic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.IsDeletedCode;
import com.ctshk.common.enums.SystemBusinessType;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.TokenUser;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.rpc.finance.req.bill.BillOperateRefundReq;
import com.ctshk.rpc.finance.service.IFinanceBillService;
import com.ctshk.rpc.order.scenic.dto.ScenicOrderCollectionDTO;
import com.ctshk.rpc.order.scenic.dto.ScenicOrderCollectionReceiptDTO;
import com.ctshk.rpc.order.scenic.dto.ScenicOrderCollectionWayDTO;
import com.ctshk.rpc.order.scenic.dto.ScenicProductSpecAttrDTO;
import com.ctshk.rpc.order.scenic.entity.ScenicOrder;
import com.ctshk.rpc.order.scenic.entity.ScenicOrderCollection;
import com.ctshk.rpc.order.scenic.entity.ScenicOrderReceipt;
import com.ctshk.rpc.order.scenic.mapper.ScenicOrderCollectionMapper;
import com.ctshk.rpc.order.scenic.mapper.ScenicOrderMapper;
import com.ctshk.rpc.order.scenic.mapper.ScenicOrderReceiptMapper;
import com.ctshk.rpc.order.scenic.req.ScenicOrderCollectionConfirmationReq;
import com.ctshk.rpc.order.scenic.req.ScenicOrderCollectionRejectReq;
import com.ctshk.rpc.order.scenic.req.ScenicOrderCollectionReq;
import com.ctshk.rpc.order.scenic.req.ScenicOrderReceiptReq;
import com.ctshk.rpc.order.scenic.service.IScenicOrderCollectionService;
import com.ctshk.rpc.scenic.dto.ScenicProductReceiptDTO;
import com.ctshk.rpc.scenic.req.ScenicProductDetailReq;
import com.ctshk.rpc.scenic.service.IScenicProductService;
import com.ctshk.rpc.system.dto.UserDTO;
import com.ctshk.rpc.system.service.ISysUserService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 门票收款明细 服务实现类
 * </p>
 *
 * @author 张志朋
 * @since 2021-02-24
 */
@DubboService
public class ScenicOrderCollectionServiceImpl extends ServiceImpl<ScenicOrderCollectionMapper, ScenicOrderCollection> implements IScenicOrderCollectionService {

    @Autowired
    private ScenicOrderCollectionMapper scenicOrderCollectionMapper;

    @Autowired
    private ScenicOrderMapper scenicOrderMapper;

    @DubboReference
    private ISysUserService iSysUserService;

    @DubboReference
    private IScenicProductService scenicProductService;
    @Autowired
    private ScenicOrderReceiptMapper scenicOrderReceiptMapper;
    @DubboReference
    private IFinanceBillService iFinanceBillService;

    @Override
    public Result<List<ScenicOrderCollectionDTO>> list(ScenicOrderCollectionReq scenicOrderCollectionReq) {
        QueryWrapper<ScenicOrderCollection> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_deleted", 0);
        queryWrapper.eq("order_id", scenicOrderCollectionReq.getOrderId());
        List<ScenicOrderCollection> list = scenicOrderCollectionMapper.selectList(queryWrapper);
        List<ScenicOrderCollectionDTO> orderCollectionDTOS = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(list)) {
            for (ScenicOrderCollection scenicOrderCollection : list) {
                ScenicOrderCollectionDTO scenicOrderTouristDTO = EntityUtil.copy(scenicOrderCollection, ScenicOrderCollectionDTO.class);
                UserDTO userDTO = null;
                try {
                    if (scenicOrderCollection.getSalerId() != null) {
                        userDTO = iSysUserService.loadUserByParam(scenicOrderCollection.getSalerId(), 1);
                        scenicOrderTouristDTO.setSalerName(userDTO.getUsername() + "/" + userDTO.getDept());
                    }
                } catch (Exception e) {
                    throw new BusinessException(SystemError.SYS_502);
                }
                orderCollectionDTOS.add(scenicOrderTouristDTO);
            }
        }
        return Result.success(orderCollectionDTOS);
    }

    @Override
    public Result<Long> confirmation(ScenicOrderCollectionConfirmationReq scenicOrderCollectionConfirmationReq, TokenUser user) {
        QueryWrapper<ScenicOrderCollection> scenicOrderCollectionQueryWrapper = new QueryWrapper<>();
        scenicOrderCollectionQueryWrapper.eq("is_deleted", IsDeletedCode.NO.getCode());
        scenicOrderCollectionQueryWrapper.eq("id", scenicOrderCollectionConfirmationReq.getId());
        ScenicOrderCollection soc = scenicOrderCollectionMapper.selectOne(scenicOrderCollectionQueryWrapper);
        if (soc != null) {
            soc.setGmtModified(LocalDateTime.now());
            soc.setModifiedId(user.getId());
            soc.setStatus(0);// 其它 --   1 驳回
            soc.setRejectInfo(" ");
            int i = scenicOrderCollectionMapper.updateById(soc);
            if (i > 0) {
                BillOperateRefundReq refundReq = new BillOperateRefundReq();
                refundReq.setBillNumber(soc.getCollectionNumber());
                refundReq.setBusinessType(SystemBusinessType.ATTRACTION_TICKET.getCode());
                refundReq.setUserId(user.getId());
                Result result = iFinanceBillService.reConfirm(refundReq);
                if (result.isSuccess()) {
                    return Result.success(soc.getId());
                } else {
                    Result.failed(SystemError.SCENIC_5019,
                            "财务再次确认接口调用失败，给定的参数为：" +
                                    soc.getCollectionNumber() + "|" +
                                    SystemBusinessType.ATTRACTION_TICKET.getCode() + "|" +
                                    user.getId()
                    );
                }
            }
        }
        return Result.failed(SystemError.SCENIC_5018);
    }

    @Override
    public Result<ScenicOrderCollectionReceiptDTO> collectionReceipt(ScenicOrderReceiptReq scenicOrderReceiptReq, TokenUser user) {
        ScenicOrder scenicOrder = scenicOrderMapper.selectById(scenicOrderReceiptReq.getOrderId());
        ScenicOrderCollectionReceiptDTO scenicOrderCollectionReceiptDTO = new ScenicOrderCollectionReceiptDTO();
        UserDTO userDTO = null;
        try {
            userDTO = iSysUserService.loadUserByParam(user.getId(), 1);
            scenicOrderCollectionReceiptDTO.setBranch(userDTO.getDept());
        } catch (Exception e) {
            throw new BusinessException(SystemError.SYS_502);
        }
        if (scenicOrder != null) {
            QueryWrapper<ScenicOrderReceipt> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("is_deleted", 0);
            queryWrapper.eq("order_id", scenicOrder.getId());
            ScenicOrderReceipt scenicOrderReceipt = scenicOrderReceiptMapper.selectOne(queryWrapper);
            scenicOrderCollectionReceiptDTO.setAttention(scenicOrderReceipt.getAttention());
            scenicOrderCollectionReceiptDTO.setRemark(scenicOrderReceipt.getRemark());
            scenicOrderCollectionReceiptDTO.setReceiptNo(scenicOrderReceipt.getReceiptNo());
            scenicOrderCollectionReceiptDTO.setBranch(scenicOrderReceipt.getBranch());
            scenicOrderCollectionReceiptDTO.setGuest(scenicOrderReceipt.getGuest());
            scenicOrderCollectionReceiptDTO.setPhone(scenicOrderReceipt.getPhone());
            scenicOrderCollectionReceiptDTO.setOrderNumber(scenicOrder.getOrderNumber());
            ScenicProductDetailReq scenicProductDetailReq = new ScenicProductDetailReq();
            scenicProductDetailReq.setId(scenicOrder.getProductId());

            Result<ScenicProductReceiptDTO> result = scenicProductService.scenicProductDetail(scenicProductDetailReq);
            if (result.isSuccess()) {
                ScenicProductReceiptDTO scenicProductReceiptDTO = result.getData();
                scenicOrderCollectionReceiptDTO.setName(scenicProductReceiptDTO.getName());
                scenicOrderCollectionReceiptDTO.setScenicProductSpecAttrDTOList(EntityUtil.copyList(scenicProductReceiptDTO.getScenicProductSpecAttrDTOList(), ScenicProductSpecAttrDTO.class));
                scenicOrderCollectionReceiptDTO.setCostPrice(scenicProductReceiptDTO.getCostPrice());
                scenicOrderCollectionReceiptDTO.setQuantity(scenicProductReceiptDTO.getQuantity());
                if (scenicProductReceiptDTO.getQuantity() != 0 && scenicProductReceiptDTO.getCostPrice() != null) {
                    scenicOrderCollectionReceiptDTO.setCostPriceTotal(scenicProductReceiptDTO.getCostPrice().multiply(new BigDecimal(scenicProductReceiptDTO.getQuantity())));
                }
            }
            scenicOrderCollectionReceiptDTO.setQueryNumber(scenicOrder.getQueryNumber());
            //收款记录
            QueryWrapper<ScenicOrderCollection> scenicOrderCollectionQueryWrapper = new QueryWrapper<>();
            scenicOrderCollectionQueryWrapper.eq("is_deleted", 0);
            scenicOrderCollectionQueryWrapper.eq("order_id", scenicOrder.getId());
            List<ScenicOrderCollection> list = scenicOrderCollectionMapper.selectList(scenicOrderCollectionQueryWrapper);
            if (CollectionUtils.isNotEmpty(list)) {
                List<ScenicOrderCollectionWayDTO> scenicOrderCollectionWayDTOArrayList = new ArrayList<>();
                for (ScenicOrderCollection collection : list) {
                    ScenicOrderCollectionWayDTO scenicOrderCollectionDTO = EntityUtil.copy(collection, ScenicOrderCollectionWayDTO.class);
                    scenicOrderCollectionWayDTOArrayList.add(scenicOrderCollectionDTO);
                }
            }
        } else {
            throw new BusinessException(SystemError.CUSTOM_ORDER_4024);
        }
        return Result.success(scenicOrderCollectionReceiptDTO);
    }

    @Override
    public Result<ScenicOrderCollectionReceiptDTO> collectionReceipts(Long orderId) {
        ScenicOrder scenicOrder = scenicOrderMapper.selectById(orderId);
        ScenicOrderCollectionReceiptDTO scenicOrderCollectionReceiptDTO = new ScenicOrderCollectionReceiptDTO();

        if (scenicOrder != null) {
            QueryWrapper<ScenicOrderReceipt> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("is_deleted", 0);
            queryWrapper.eq("order_id", scenicOrder.getId());
            ScenicOrderReceipt scenicOrderReceipt = scenicOrderReceiptMapper.selectOne(queryWrapper);
            scenicOrderCollectionReceiptDTO.setAttention(scenicOrderReceipt.getAttention());
            scenicOrderCollectionReceiptDTO.setRemark(scenicOrderReceipt.getRemark());
            scenicOrderCollectionReceiptDTO.setReceiptNo(scenicOrderReceipt.getReceiptNo());
            scenicOrderCollectionReceiptDTO.setBranch(scenicOrderReceipt.getBranch());
            scenicOrderCollectionReceiptDTO.setGuest(scenicOrderReceipt.getGuest());
            scenicOrderCollectionReceiptDTO.setPhone(scenicOrderReceipt.getPhone());
            scenicOrderCollectionReceiptDTO.setOrderNumber(scenicOrder.getOrderNumber());
            ScenicProductDetailReq scenicProductDetailReq = new ScenicProductDetailReq();
            scenicProductDetailReq.setId(scenicOrder.getProductId());

            Result<ScenicProductReceiptDTO> result = scenicProductService.scenicProductDetail(scenicProductDetailReq);
            if (result.isSuccess()) {
                ScenicProductReceiptDTO scenicProductReceiptDTO = result.getData();
                scenicOrderCollectionReceiptDTO.setName(scenicProductReceiptDTO.getName());
                scenicOrderCollectionReceiptDTO.setScenicProductSpecAttrDTOList(EntityUtil.copyList(scenicProductReceiptDTO.getScenicProductSpecAttrDTOList(), ScenicProductSpecAttrDTO.class));
                scenicOrderCollectionReceiptDTO.setCostPrice(scenicProductReceiptDTO.getCostPrice());
                scenicOrderCollectionReceiptDTO.setQuantity(scenicProductReceiptDTO.getQuantity());
                if (scenicProductReceiptDTO.getQuantity() != 0 && scenicProductReceiptDTO.getCostPrice() != null) {
                    scenicOrderCollectionReceiptDTO.setCostPriceTotal(scenicProductReceiptDTO.getCostPrice().multiply(new BigDecimal(scenicProductReceiptDTO.getQuantity())));
                }
            }
            scenicOrderCollectionReceiptDTO.setQueryNumber(scenicOrder.getQueryNumber());
            //收款记录
            QueryWrapper<ScenicOrderCollection> scenicOrderCollectionQueryWrapper = new QueryWrapper<>();
            scenicOrderCollectionQueryWrapper.eq("is_deleted", 0);
            scenicOrderCollectionQueryWrapper.eq("order_id", scenicOrder.getId());
            List<ScenicOrderCollection> list = scenicOrderCollectionMapper.quertOrderId(orderId);
            if (CollectionUtils.isNotEmpty(list)) {
                /*List<ScenicOrderCollectionWayDTO> scenicOrderCollectionWayDTOArrayList = new ArrayList<>();
                for (ScenicOrderCollection collection : list) {
                    ScenicOrderCollectionWayDTO scenicOrderCollectionDTO = EntityUtil.copy(collection, ScenicOrderCollectionWayDTO.class);
                    scenicOrderCollectionWayDTOArrayList.add(scenicOrderCollectionDTO);
                }*/
                scenicOrderCollectionReceiptDTO.setPayWay(list.get(0).getCollectionWay());
                scenicOrderCollectionReceiptDTO.setGmtCreate(list.get(0).getGmtCreate());
            }
        } else {
            throw new BusinessException(SystemError.CUSTOM_ORDER_4024);
        }
        return Result.success(scenicOrderCollectionReceiptDTO);
    }

    @Override
    public Result reject(ScenicOrderCollectionRejectReq req, Long userId) {
        ScenicOrderCollection scenicOrderCollection = scenicOrderCollectionMapper.selectById(req.getCollectionNumber());
        if (scenicOrderCollection != null) {
            scenicOrderCollection.setStatus(0);
            scenicOrderCollection.setModifiedId(userId);
            scenicOrderCollection.setGmtModified(LocalDateTime.now());
            scenicOrderCollection.setRejectInfo(req.getRejectInfo());
            scenicOrderCollectionMapper.updateById(scenicOrderCollection);
        } else {
            throw new BusinessException(SystemError.CUSTOM_ORDER_4024);
        }
        return Result.success();
    }

    @Override
    public Result confirmCollection(ScenicOrderCollectionRejectReq req, Long userId) {
        QueryWrapper<ScenicOrderCollection> scenicOrderCollectionQueryWrapper = new QueryWrapper<>();
        scenicOrderCollectionQueryWrapper.eq("is_deleted", 0);
        scenicOrderCollectionQueryWrapper.eq("collection_number", req.getCollectionNumber());
        ScenicOrderCollection scenicOrderCollection = scenicOrderCollectionMapper.selectOne(scenicOrderCollectionQueryWrapper);
        scenicOrderCollection.setGmtModified(LocalDateTime.now());
        scenicOrderCollection.setModifiedId(userId);
        scenicOrderCollection.setSalerId(userId);
        UserDTO userDTO = null;
        try {
            userDTO = iSysUserService.loadUserByParam(userId, 1);
            scenicOrderCollection.setSalerName(userDTO.getCnName());
        } catch (Exception e) {
            throw new BusinessException(SystemError.SYS_502);
        }
        scenicOrderCollection.setStatus(0);
        scenicOrderCollectionMapper.updateById(scenicOrderCollection);
        return Result.success(scenicOrderCollection.getId());
    }

}
